package com.base.cn.platform.os.controller.user.user;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.log.aop.AdminModuleEnum;
import com.base.cn.platform.os.common.log.aop.OpLog;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.course.agent.user.AgentUserService;
import com.base.cn.platform.os.service.course.classes.ClassesService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountHistoryService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.manage.user.login.UserLoginService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.base.cn.platform.os.service.manage.user.user.CuserProfileService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 后台用户管理
 *
 * @author ll
 * @create 2018-04-09-19:08
 */
@Controller
@RequestMapping("/admin/user/cus")
public class AdminUserController extends AdminBaseController {

    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private AgentUserService agentUserService;
    @Autowired
    private CusUserAccountHistoryService cusUserAccountHistoryService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CuserProfileService cuserProfileService;
    @Autowired
    private Environment environment;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;

    /**
     * 初始化列表页面
     *
     * @return
     */
    @RequestMapping("/userList")
    public String userList(Model model) {
        UserExpandFrom[] userExpandFromList = UserExpandFrom.values();
        model.addAttribute("userExpandFromList", userExpandFromList);
        return resultPage("/user/user/user_list");
    }

    /**
     * 强制学员退出登录
     *
     * @param request
     * @param userId  用户ID
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/forceUserSignOut")
    @ResponseBody
    public Map<String, Object> forceUserSignOut(HttpServletRequest request,
                                                @RequestParam("userId") BigDecimal userId) {
        return userLoginService.forceUserSignOut(userId);
    }

    /**
     * 加载数据列表
     *
     * @param model Model
     * @return 列表页面
     * @param(value = "subjectData",defaultValue = "false",required = false) boolean subjectData,
     * @param(value = "userAddresses",defaultValue = "false",required = false) boolean userAddresses,
     * @param(value = "expRule",defaultValue = "false",required = false) boolean expRule,
     * @param(value = "gradeConfig",defaultValue = "false",required = false)  boolean gradeConfig,
     * @param(value = "integral",defaultValue = "false",required = false)  boolean integral,
     * @param(value = "userMember",defaultValue = "false",required = false)  boolean userMember,
     * @param(value = "expAccount",defaultValue = "false",required = false)  boolean expAccount
     */
    @RequestMapping("/ajaxUserListPage")
    public String ajaxUserListPage(Model model,
                                   @RequestBody Map<String, Object> params,
                                   @RequestParam(value = "currentPage", defaultValue = "1", required = false) int currentPage) {
        Map<String, Object> dataMap = cusUserService.queryUserListPage(params, currentPage, false, false, false, false, false, false, false);
        if (ObjectUtils.isNotEmpty(dataMap) && ObjectUtils.isNotEmpty(dataMap.get("list"))) {
            List<Map<String, Object>> users = (List<Map<String, Object>>) dataMap.get("list");
            String ids = users.stream().map(e -> e.get("id").toString()).collect(Collectors.joining(","));
            Map<String, Object> userProfileMapList = cuserProfileService.findUserProfileMapList(ids);
            for (Map user : users) {
                user.put("ProfileMap", userProfileMapList.get(user.get("id").toString()));
            }
        }
        model.addAttribute("dataMap", dataMap);
        model.addAttribute("userExpandFromList", UserExpandFrom.values());
        return resultPage("/user/user/user_ajax_list");
    }


    /**
     * 去添加页面
     *
     * @return
     */
    @RequestMapping("/saveUser")
    public String saveUser() {
        return resultPage("/user/user/user_create");
    }

    /***
     * 添加学员
     * @param user
     * @return
     */
    @RequestMapping("/ajaxSaveUser")
    @ResponseBody
    @OpLog(module = AdminModuleEnum.USER, action = "添加学员")
    public Map<String, Object> ajaxSaveUser(@RequestBody Map<String, Object> user) {
        //用户数据
        user.put("registerFrom", UserExpandFrom.adminFrom.getKey());
        return cusUserService.saveUser(user, true, user.get("courseIds").toString());
    }

    /**
     * 修改用户状态
     *
     * @param userIds
     * @param status
     * @return
     */
    @RequestMapping("/updateCusUserStatus")
    @ResponseBody
    @OpLog(module = AdminModuleEnum.USER, action = "修改学员用户状态")
    public Map<String, Object> updateCusUserStatus(@RequestParam("userIds") String userIds,
                                                   @RequestParam("status") Integer status) {
        return cusUserService.updateCusUserStatus(userIds, status);
    }

    /**
     * 去引入学员页面
     *
     * @return
     */
    @RequestMapping("/importUser")
    public String importUser() {
        return resultPage("/user/user/students_sys_import");
    }


    /**
     * 用户详情
     *
     * @param userId
     * @return
     */
    @RequestMapping("/userInfo")
    public String userInfo(Model model, @RequestParam("userId") BigDecimal userId) {
        Map<String, Object> dataMap = cusUserService.userInfo(userId, false, true, true,
                true, true, true, true);
        if (ObjectUtils.isNotEmpty(dataMap)) {
            Integer studyTotalTime = (Integer) dataMap.get("studyTotalTime");
            studyTotalTime = studyTotalTime / 60;
            dataMap.put("studyTotalTime", studyTotalTime);
            Map<String, Object> userAccountHistoryMap = new HashMap<>();
            userAccountHistoryMap.put("userId", userId);
            userAccountHistoryMap.put("bizType", "SHOP");
            List<Map<String, Object>> userAccountHistoryList = cusUserAccountHistoryService.findUserAccountHistoryList(userAccountHistoryMap, false);
            BigDecimal amountOfConsumption = new BigDecimal(0);
            for (Map<String, Object> userAccountHistory : userAccountHistoryList) {
                amountOfConsumption = amountOfConsumption.add(new BigDecimal(Double.toString((Double) userAccountHistory.get("trxAmount"))));
            }
            dataMap.put("amountOfConsumption", amountOfConsumption);
            model.addAttribute("user", dataMap);
        } else {
            model.addAttribute("user", new HashMap<String, Object>());
        }
        //获取用户专业
        Map<String, List<Map<String, Object>>> userAcademic = cusUserService.findUserAcademic(userId);
        //获取用户班级
        List<Map<String, Object>> classesPersonalList = classesService.findClassesPersonalList(userId);
        //获取第三方账号信息
        //获取用户的第三代账号
        dataMap.put("cuserProfile", cuserProfileService.findUserProfile(userId));
        model.addAttribute("userAcademic", userAcademic);
        model.addAttribute("userClassList", classesPersonalList);
        UserExpandFrom[] userExpandFromList = UserExpandFrom.values();
        model.addAttribute("userExpandFromList", userExpandFromList);
        // 获取该用户积分统计
        model.addAttribute("userIntegral", cusUserIntegralService.queryUserIntegralByUserId(userId));
        UserCondition condition = new UserCondition();
        condition.setId(userId);
        condition.setNotStudy(true);
        Map<String, Object> userStudy = cusUserService.userStudyInfo(condition);
        model.addAttribute("userStudy", userStudy);
        return resultPage("/user/user/user_info");
    }

    /**
     * 搜索受邀人数和收益
     *
     * @param userId
     * @return
     */
    @RequestMapping("/personsNumIncome")
    @ResponseBody
    public Map<String, Object> personsNumIncome(@RequestParam("userId") BigDecimal userId) {
        Map<String, Object> dataMap = agentUserService.findAgentUserByUserId(userId, true, false, false);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 初始化选择用户列表
     *
     * @param subjectIds 课程专业查询条件
     * @return 列表页面
     */
    @RequestMapping("/selectUserList")
    public String selectUserList(Model model,
                                 @RequestParam(value = "selectType", required = false, defaultValue = "radio") String selectType,
                                 @RequestParam(value = "subjectIds", required = false, defaultValue = "") String subjectIds) {
        model.addAttribute("selectType", selectType);
        model.addAttribute("subjectIds", subjectIds);
        model.addAttribute("userExpandFromList", UserExpandFrom.values());

        return resultPage("/user/user/select_user_list");
    }

    /**
     * 获取选择课程数据
     *
     * @param params
     * @param currentPage 当前页码
     * @return 列表页面
     */
    @RequestMapping("/ajaxSelectUserList")
    public String ajaxSelectUserList(Model model,
                                     @RequestBody Map<String, Object> params,
                                     @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage) {
        params.put("status", 1);//只查询状态正常的
        Map<String, Object> dataMap = cusUserService.queryUserListPage(params, currentPage, true, false, false, false, false, false, false);
        model.addAttribute("dataMap", dataMap);
        model.addAttribute("selectType", params.get("selectType"));
        UserExpandFrom[] userExpandFromList = UserExpandFrom.values();
        model.addAttribute("userExpandFromList", userExpandFromList);
        return resultPage("/user/user/select_user_ajax_list");
    }

    /**
     * 重置密码
     *
     * @param userId
     * @return
     */
    @RequestMapping("/resetPassword")
    @ResponseBody
    @OpLog(module = AdminModuleEnum.USER, action = "重置学员账号密码")
    public Map<String, Object> resetPassword(@RequestParam("userId") BigDecimal userId,
                                             @RequestParam("rPassword") String rPassword) {
        return cusUserService.resetPassword(userId, rPassword);
    }


    /**
     * 验证账号是否存在
     *
     * @param account
     * @return
     */
    @RequestMapping("/verifyAccount")
    @ResponseBody
    public Map<String, Object> verifyAccount(@RequestParam("account") String account) {
        return cusUserService.verifyAccount(account);
    }

    /**
     * 选择专业/科目页面
     * @return
     */
    @RequestMapping("/initSelectSubject")
    public String initSelectSubject(){
        return resultPage("/user/user/students_subject_import");
    }

    /**
     * 下载用户导入模板
     *
     * @return ResponseEntity<byte   [   ]>
     */
    @RequestMapping("/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate() throws Exception {

        String url = environment.getProperty("static.path") + "/admin/business/common/import-user/import_student.xls";
        String fileName = "user-import-" + System.currentTimeMillis() + ".xls";
        RestTemplate rest = new RestTemplate();
        HttpEntity requestEntity = new HttpEntity(null, new LinkedMultiValueMap<>());
        ResponseEntity<byte[]> exchange = rest.exchange(url, HttpMethod.GET, requestEntity, byte[].class);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(exchange.getBody(), headers, HttpStatus.OK);
    }


    @RequestMapping(value = "/ajaxImportUserExcel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    @OpLog(module = AdminModuleEnum.USER, action = "导入学员")
    public Map<String, Object> importUserExcels(HttpServletRequest request,
                                                @RequestPart(value = "file") MultipartFile file) {

        String referer = request.getHeader("referer");
        String subjectIds = request.getParameter("subjectIds");
        if (!StringUtils.isNotEmpty(referer)) {
            return ResultUtil.SUCCESS(null, "非法请求，上传失败");
        }

        HSSFWorkbook wookbook = null;
        try {
            wookbook = new HSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            return ResultUtil.SUCCESS(null, "读取xls表格数据错误");
        }
        //只读取sheet1
        HSSFSheet sheet = wookbook.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows(); //excel中实际行数
        if (rows == 0) {
            return ResultUtil.SUCCESS(null, "xls表格中没有填写数据");
        }
        if (rows > 301) {
            return ResultUtil.SUCCESS(null, "xls表中的数据不能多于300行");
        }
        //验证数据
        Map<String, Object> checkResult = checkExcelUser(sheet,subjectIds);
        Map<String, Map<String, Object>> userMap = (Map<String, Map<String, Object>>) checkResult.get("userMap");
        StringBuilder errorMsg = new StringBuilder((String) checkResult.get("errorMsg"));
        if (ObjectUtils.isEmpty(userMap)) {
            errorMsg.append("=====导入结果=====<br/>").append("成功导入 <b>0</b> 条数据");
            return ResultUtil.SUCCESS("导入成功", errorMsg.toString());
        }
        Map<String, Object> createResult = this.createExcelUser(userMap);
        errorMsg.append(ObjectUtils.isNotEmpty(createResult.get("entity").toString()) ? createResult.get("entity") : "");
        if (!checkResult.get("creatGifts").toString().equals("0")) {
            errorMsg.append("<br>为已存在的用户赠送课程 <b>" + checkResult.get("creatGifts") + "</b> 条数据");
        }
        return ResultUtil.SUCCESS("导入成功", errorMsg.toString());
    }


    /**
     * 上传学员
     *
     * @param userMap
     * @return
     */
    private Map<String, Object> createExcelUser(@RequestBody Map<String, Map<String, Object>> userMap) {
        if (ObjectUtils.isEmpty(userMap)) {
            return ResultUtil.SUCCESS("导入成功", "=====导入结果=====<br/>成功导入 <b>0</b> 条数据");
        }
        long startTime = System.currentTimeMillis();
        // 遍历创建用户,赠送课程和会员
        int successCount = 0;
        List<String> successRowList = new ArrayList<>();
        List<Map<String, Object>> batchUser = new ArrayList<>();
        StringBuilder errorMsg = new StringBuilder();
        errorMsg.append("=====用户创建 开始=====<br/>");
        for (Map.Entry<String, Map<String, Object>> userEntry : userMap.entrySet()) {
            // 用户对应excel行号
            String rowNumber = userEntry.getKey();
            Map<String, Object> cusUser = userEntry.getValue();
            //区分创建该学员时是否需要赠送课程 不需要赠送课程的学员进行批量添加
            if (ObjectUtils.isEmpty(cusUser.get("courseIds"))) {
                successCount++;
                batchUser.add(cusUser);
                continue;
            }
            Map<String, Object> excelUser = cusUserService.createExcelUser(cusUser);
            if (ResultUtil.getSuccess(excelUser)) {
                successCount++;
                successRowList.add(rowNumber);
            } else {
                errorMsg.append("第" + rowNumber + "行" + ResultUtil.getMessage(excelUser));
            }
        }
        if (ObjectUtils.isNotEmpty(batchUser)) {
            cusUserService.createUser(batchUser);
        }
        errorMsg.append("=====用户创建 结束=====<br/><br/>");
        errorMsg.append("=====导入结果=====<br/>").append("成功创建学员<b>").append(successCount).append("</b> 条数据");
        String successRowStr = successRowList.stream().collect(Collectors.joining(","));
        errorMsg.append("成功导入的行号为: ").append(successRowStr);

        logger.info("------------------------批量导入学员-耗时：" + ((System.currentTimeMillis() - startTime) / 1000) + "秒。");
        return ResultUtil.SUCCESS("导入成功", errorMsg);
    }

    /**
     * 校验excel表格所有信息
     *
     * @param sheet
     * @return
     */
    public Map<String, Object> checkExcelUser(HSSFSheet sheet,String subjectIds) {
        int creatGifts = 0;
        // 通过字段校验的用户map
        Map<String, Map<String, Object>> userMap = new HashMap<>();
        // 全局报错信息
        StringBuilder totalErrorMsg = new StringBuilder();
        Set<String> mobileSet = new HashSet<>();
        Set<String> accountSet = new HashSet<>();
        Set<String> emailSet = new HashSet<>();
        Set<Integer> courseSet = new HashSet<>();
        totalErrorMsg.append("=====数据格式检查 开始=====</br>");
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 1; i <= rows; i++) {
            // 读取行为第二行开始
            HSSFRow row = sheet.getRow(i);
            if (row != null) {
                // 如果是空行直接跳过
                Iterator<Cell> it = row.iterator();
                boolean isBlank = true;
                while (it.hasNext() && isBlank) {
                    Cell c = it.next();
                    c.setCellType(CellType.STRING);
                    if (c.getCellType() == HSSFCell.CELL_TYPE_BLANK || StringUtils.isEmpty(c.getStringCellValue())) {
                        continue;
                    }
                    isBlank = false;
                }
                if (isBlank) {
                    continue;
                }

                Map<String, Object> user = new HashMap<>();
                StringBuilder rowErrorMsg = new StringBuilder();
                int rowNumber = i + 1;
                try {
                    row.getPhysicalNumberOfCells();
                    // **读取行中的列**
                    // 获取并校验手机号格式, 校验通过存入map, 准备唯一性校验
                    HSSFCell cell = row.getCell((short) 0);//手机号
                    String mobile = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        mobile = cell.getStringCellValue().trim();
                    }
                    if (StringUtils.isEmpty(mobile)) {
                        rowErrorMsg.append("第" + rowNumber + "行中的手机号不能为空! </br>");
                    } else if (!StringUtils.isMobile(mobile.trim())) {
                        rowErrorMsg.append("第" + rowNumber + "行中的手机号格式不正确! </br>");
                    } else {
                        user.put("mobile", mobile);
                        user.put("mobileIsavalible", 1);
                        mobileSet.add(mobile);
                    }

                    // 获取并校验账号格式, 校验通过存入map, 准备唯一性校验
                    cell = row.getCell((short) 1);
                    String loginAccount = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        loginAccount = cell.getStringCellValue().trim();
                    }
                    if (StringUtils.isNotEmpty(loginAccount)) {
                        if (!loginAccount.matches("^[A-Za-z0-9]{6,20}$")) {
                            rowErrorMsg.append("第" + rowNumber + "行账号错误，账号只能是英文与数字组合，且长度6-20位！</br>");
                        } else {
                            user.put("loginAccount", loginAccount);
                            accountSet.add(loginAccount);
                        }
                    }

                    // 获取并校验邮箱格式, 校验通过存入map, 准备唯一性校验
                    cell = row.getCell((short) 2);
                    String email = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        email = cell.getStringCellValue().trim();
                    }
                    if (StringUtils.isNotEmpty(email)) {
                        if (!StringUtils.isEmail(email)) {
                            rowErrorMsg.append("第" + rowNumber + "行中的邮箱格式不正确! </br>");
                        } else {
                            user.put("email", email);
                            user.put("emailIsavalible", 1);
                            emailSet.add(email);
                        }
                    }
                    // 获取并校验密码
                    cell = row.getCell((short) 3);
                    String password = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        password = cell.getStringCellValue().trim();
                    }
                    if (StringUtils.isEmpty(password)) {
                        password = "111111";
                    } else if (!password.matches("^.{6,20}$")) {
                        rowErrorMsg.append("第" + rowNumber + "行密码错误, 密码长度必须为6-20位！</br>");
                    }
                    user.put("password", password);

                    // 获取并校验赠送课程id
                    cell = row.getCell((short) 4);
                    String courseIds = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        courseIds = cell.getStringCellValue().trim();
                    }
                    if (StringUtils.isNotEmpty(courseIds)) {
                        courseIds = StringUtils.subHeadTailString(courseIds, "#").trim();
                        if (StringUtils.isNotEmpty(courseIds) && courseIds.matches("^\\d+(#\\d+)*$")) {
                            Arrays.stream(courseIds.split("#")).filter(StringUtils::isNumber).map(Integer::parseInt).forEach(e -> courseSet.add(e));
                            user.put("courseIds", courseIds.replaceAll("#", ","));
                        } else {
                            rowErrorMsg.append("第" + rowNumber + "行中的赠送课程id格式不正确! </br>");
                        }
                    }
                    // 如果存在出错的信息, 报错错误信息并, 跳过此行数据不保存
                    if (StringUtils.isNotEmpty(rowErrorMsg.toString())) {
                        totalErrorMsg.append(rowErrorMsg);
                        continue;
                    }
                    user.put("registerFrom", UserExpandFrom.adminFrom.toString());
                    user.put("isavalible", 1);
                    user.put("status", 1);
                    user.put("subjectIds",subjectIds);
                    userMap.put(String.valueOf(rowNumber), user);
                } catch (Exception e) {
                    e.printStackTrace();
                    rowErrorMsg.append("第" + rowNumber + "行数据检查异常! </br>");
                    totalErrorMsg.append(rowErrorMsg);
                    continue;
                }
            }
        }

        totalErrorMsg.append("=====数据格式检查 结束=====</br></br>");
        totalErrorMsg.append("=====数据内容有效性校验 开始=====</br>");
        List<Map<String, Object>> existing = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(userMap)) {
            // 遍历校验 手机号, 账号和邮箱是否重复, 课程id是否存在
            // 查询所有需要校验的手机号,账号和邮箱, 将已经存在的值保存在set中
            if (ObjectUtils.isNotEmpty(mobileSet)) {
                String mobileStr = mobileSet.stream().collect(Collectors.joining("','", "'", "'"));
                List<Map<String, Object>> existMobileList = cusUserService.queryUserByFieldValueStr("mobile", mobileStr);
                mobileSet.clear();
                if (ObjectUtils.isNotEmpty(existMobileList)) {
                    existing.addAll(existMobileList);
                    mobileSet = existMobileList.stream().map(e -> e.get("mobile").toString()).collect(Collectors.toSet());
                }
            }
            if (ObjectUtils.isNotEmpty(accountSet)) {
                String accountStr = accountSet.stream().collect(Collectors.joining("','", "'", "'"));
                List<Map<String, Object>> existAccountList = cusUserService.queryUserByFieldValueStr("loginAccount", accountStr);
                accountSet.clear();
                if (ObjectUtils.isNotEmpty(existAccountList)) {
                    existing.addAll(existAccountList);
                    accountSet = existAccountList.stream().map(e -> e.get("loginAccount").toString()).collect(Collectors.toSet());
                }
            }
            if (ObjectUtils.isNotEmpty(emailSet)) {
                String emailStr = emailSet.stream().collect(Collectors.joining("','", "'", "'"));
                List<Map<String, Object>> existEmailList = cusUserService.queryUserByFieldValueStr("email", emailStr);
                emailSet.clear();
                if (ObjectUtils.isNotEmpty(existEmailList)) {
                    existing.addAll(existEmailList);
                    emailSet = existEmailList.stream().map(e -> e.get("email").toString()).collect(Collectors.toSet());
                }
            }

            // 查询所有需要赠送的课程id和会员id对应的课程和会员
            Map<BigDecimal, Map<String, Object>> courseMap = null;
            if (ObjectUtils.isNotEmpty(courseSet)) {
                String courseIds = courseSet.stream().map(e -> e.toString()).collect(Collectors.joining(","));
                courseMap = courseService.findCourseToMapByIds(courseIds, false, false, false);
            }
            Map<String, Map<String, Object>> userMapTo = new HashMap<>();
            userMapTo.putAll(userMap);
            // 遍历校验 手机号, 账号和邮箱是否重复, 课程id和会员id是否存在
            for (Iterator<Map.Entry<String, Map<String, Object>>> it = userMap.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<String, Map<String, Object>> entry = it.next();
                StringBuilder errorMsg = new StringBuilder();
                String rowNumber = entry.getKey();
                Map<String, Object> cusUser = entry.getValue();
                Map<String, Object> createCourseUser = new HashMap<>();
                try {
                    boolean isMobile = false;
                    boolean isAccount = false;
                    boolean isEmail = false;
                    if (StringUtils.isNotEmpty(cusUser.get("mobile")) && mobileSet.contains(cusUser.get("mobile"))) {
                        errorMsg.append("第" + rowNumber + "行中的手机号码:" + cusUser.get("mobile") + " 已存在 </br>");
                        isMobile = true;
                    }
                    if (StringUtils.isNotEmpty(cusUser.get("loginAccount")) && accountSet.contains(cusUser.get("loginAccount"))) {
                        errorMsg.append("第" + rowNumber + "行中的账号名:" + cusUser.get("loginAccount") + " 已存在 </br>");
                        isAccount = true;
                    }
                    if (StringUtils.isNotEmpty(cusUser.get("email")) && emailSet.contains(cusUser.get("email"))) {
                        errorMsg.append("第" + rowNumber + "行中的邮箱:" + cusUser.get("email") + " 已存在 </br>");
                        isEmail = true;
                    }
                    if (ObjectUtils.isNotEmpty(existing)) {
                        if (isMobile) {
                            for (Map<String, Object> user : existing) {
                                if (user.get("mobile").equals(cusUser.get("mobile"))) {
                                    createCourseUser.put("userId", user.get("id"));
                                }
                            }
                        } else if (isAccount) {
                            for (Map<String, Object> user : existing) {
                                if (user.get("account").equals(cusUser.get("loginAccount"))) {
                                    createCourseUser.put("userId", user.get("id"));
                                }
                            }
                        } else if (isEmail) {
                            for (Map<String, Object> user : existing) {
                                if (user.get("email").equals(cusUser.get("email"))) {
                                    createCourseUser.put("userId", user.get("id"));
                                }
                            }
                        }
                    }
                    boolean isCourse = true;
                    if (StringUtils.isNotEmpty(cusUser.get("courseIds"))) {
                        for (String s : cusUser.get("courseIds").toString().split(",")) {
                            if (ObjectUtils.isEmpty(courseMap) || !courseMap.containsKey(new BigDecimal(s))) {
                                errorMsg.append("第" + rowNumber + "行中的赠送课程id:" + s + " 不存在 </br>");
                                isCourse = false;
                            }
                        }
                    }
                    if (ObjectUtils.isNotEmpty(createCourseUser)) {
                        if (isCourse) {
                            createCourseUser.put("courseIds", cusUser.get("courseIds"));
                        }
                        if (ObjectUtils.isNotEmpty(createCourseUser.get("courseIds"))) {
                            String s = cusUserService.creatGifts(createCourseUser);
                            if (StringUtils.isNotEmpty(s)) {
                                errorMsg.append("第" + rowNumber + "行  " + s + "</br>");
                            } else {
                                creatGifts += 1;
                                errorMsg.append("第" + rowNumber + "行中用户的信息已存在赠送商品成功</br>");
                            }
                        }
                    }
                    for (Map.Entry<String, Map<String, Object>> m : userMapTo.entrySet()) {
                        if (!entry.getKey().equals(m.getKey())) {
                            if (StringUtils.isNotEmpty(cusUser.get("mobile")) && m.getValue().get("mobile").toString().equals(cusUser.get("mobile"))) {
                                errorMsg.append("第" + rowNumber + "行与第" + m.getKey() + "行手机号重复" + cusUser.get("mobile") + "</br>");
                            }
                            if (StringUtils.isNotEmpty(cusUser.get("mobile")) && StringUtils.isNotEmpty( m.getValue().get("loginAccount")) && m.getValue().get("loginAccount").toString().equals(cusUser.get("mobile"))) {
                                errorMsg.append("第" + rowNumber + "行与第" + m.getKey() + "行数据异常");
                            }
                            if (!entry.getKey().equals(m.getKey())) {
                                if (StringUtils.isNotEmpty(cusUser.get("loginAccount")) && m.getValue().get("loginAccount").toString().equals(cusUser.get("loginAccount"))) {
                                    errorMsg.append("第" + rowNumber + "行与第" + m.getKey() + "行账号重复" + cusUser.get("loginAccount") + "</br>");
                                }
                            }
                            if (!entry.getKey().equals(m.getKey())) {
                                if (StringUtils.isNotEmpty(cusUser.get("email")) && m.getValue().get("email").toString().equals(cusUser.get("email"))) {
                                    errorMsg.append("第" + rowNumber + "行与第" + m.getKey() + "行邮箱重复" + cusUser.get("email") + "</br>");
                                }
                            }
                        }
                    }
                    // 如果存在报错, 将这条用户信息移除
                    if (StringUtils.isNotEmpty(errorMsg.toString())) {
                        totalErrorMsg.append(errorMsg);
                        it.remove();
                    }
                } catch (Exception e) {
                    errorMsg.append("第" + rowNumber + "行数据校验异常! </br>");
                    totalErrorMsg.append(errorMsg);
                    it.remove();
                }
            }
        }
        totalErrorMsg.append("=====数据内容有效性校验 结束=====</br></br>");

        Map<String, Object> result = new HashMap<>();
        result.put("errorMsg", totalErrorMsg.toString());
        result.put("userMap", userMap);
        result.put("creatGifts", creatGifts);
        return result;
    }
}
